/**
* C Rush OS
* 60-330 Final Assignment
* Submitted by:
*	Joseph Greaves
*	Benjamin Iannetta
*	Paul Wolak
*	
* CPU:
*	defines a simple, single core, 32bit processor that
*	is utilized by a process.
*/

//imports
import java.util.*;

public class CPU{
	//instance variables
	public static boolean inUse=false;
	private String [] exceptions = {"Divide by zero exception", "Array out ofbounds", "Segmentation fault","Time exceeded exception","Stack overflowexception", "Resource usage exception", "Instruction exception"};

	public boolean isAvailable(){
		return !inUse;
	}
	
	public boolean setToBusy(){
		return inUse=true;
	}
	
	public boolean setToFree(){
		return inUse=false;
	}

	//Executes a process
	//May generate an exception, returns false if this is the case
	public int execute(Process running){
		Random generator = new Random();
		int temp2,temp3;
		int temp = generator.nextInt(60000000);
		
		//throw an exception if temp<6
		if(temp < 6){
			Kernel.writeToLog("Exception thrown: "+ exceptions[temp] + " in Process Number: "+running.getPno()+".");	
			System.out.println("Exception thrown: "+ exceptions[temp] + " in Process Number: "+running.getPno()+".");
			return -1;
		}//throw an exception if temp<66and >6
		else if(temp<6666){
			temp2=generator.nextInt(6);
			for(int x=0;x<temp2;x++) {
				temp3=generator.nextInt(6);
				if(running.pcb.devicesNeeded[temp3]==0){
					running.pcb.devicesNeeded[temp3]=1;
				}
				else{
					x--;
				}
			}	
			return 1;
		}
		
		running.pcb.burstLengthRemaining--;
		return 0;
	}
}
